package com.googlecode.maninman.framework.servlet;

import java.io.Serializable;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

public class StandardSession implements HttpSession, Serializable{
	
	private String sessionId;
	private Map<String, Object> session;
	private long createTime;
	private long lastAccessTime;
	private int maxInactiveInterval;
	private ServletContext servletContext;
	
	public StandardSession(String sessionId, ServletContext servletContext) {
		this.sessionId = sessionId;
		session = new HashMap<String, Object>();
		this.createTime = System.currentTimeMillis();
		this.lastAccessTime = createTime;
		this.servletContext = servletContext;
	}

	@Override
	public Object getAttribute(String attr) {
		//TODO
		//先从cache读取，最后需更新时间
		return session.get(attr);
	}

	@Override
	public Enumeration<String> getAttributeNames() {
		return Collections.enumeration(session.keySet());
	}

	@Override
	public long getCreationTime() {
		return createTime;
	}

	@Override
	public String getId() {
		return sessionId;
	}

	@Override
	public long getLastAccessedTime() {
		return lastAccessTime;
	}

	@Override
	public int getMaxInactiveInterval() {
		return maxInactiveInterval;
	}

	@Override
	public ServletContext getServletContext() {
		return servletContext;
	}

	@Override
	public HttpSessionContext getSessionContext() {
		throw new UnsupportedOperationException();
	}

	@Override
	@Deprecated
	public Object getValue(String attr) {
		return getAttribute(attr);
	}

	@Override
	@Deprecated
	public String[] getValueNames() {
		return session.entrySet().toArray(new String[0]);
	}

	@Override
	public void invalidate() {
		session.clear();
		//TODO 更新缓存
	}

	@Override
	public boolean isNew() {
		return false;
	}

	@Override
	@Deprecated
	public void putValue(String attr, Object val) {
		setAttribute(attr, val);
	}

	@Override
	public void removeAttribute(String attr) {
		session.remove(attr);
		//TODO 更新缓存
	}

	@Override
	@Deprecated
	public void removeValue(String attr) {
		session.remove(attr);
	}

	@Override
	public void setAttribute(String attr, Object val) {
		session.put(attr, val);
		//TODO 更新缓存
	}

	@Override
	public void setMaxInactiveInterval(int maxInactiveInterval) {
		this.maxInactiveInterval = maxInactiveInterval;
	}
	
}
